<template>
  <div>
    <div class="flex-row p-3 bm-3">
      <div class="flex mr-3"
           @click="onPick(1)">
        <text class="text-center mb-3 text-muted">身份证正面</text>
        <div class="bg-white rounded p-3">
          <image class="id-image"
                 :src="frontImage"
                 @load="onFrontImage"></image>
        </div>
      </div>
      <div class="flex"
           @click="onPick(2)">
        <text class="text-center mb-3 text-muted">身份证正面</text>
        <div class="bg-white rounded p-3">
          <image class="id-image"
                 :src="backImage"></image>
        </div>
      </div>
    </div>

    <vm-cell label="真实姓名"
             :hasTopBorder="true">
      <input slot="title"
             placeholder="请输入真实姓名"
             v-model="realName"
             class="input" />
    </vm-cell>

    <vm-cell label="真实姓名">
      <input slot="title"
             placeholder="请输入身份证号码"
             v-model="idCode"
             class="input" />
    </vm-cell>

    <div class="p-3 flex-row mb-3">
      <text class="icon text-muted mr-1"
            style="font-size: 48px;">&#xe785;</text>
      <text class="text-muted small flex">温馨提示：需头发不遮住双耳，勿佩戴眼镜，并确保证件信息清晰可见</text>
    </div>

    <vm-button text="保存"
               @buttonClicked="submit"></vm-button>
  </div>
</template>
<script>
import VmCell from '../../components/vm-cell.vue'
import VmButton from '../../components/vm-button.vue'
const bmImage = weex.requireModule('bmImage')

export default {
  components: {
    VmCell,
    VmButton
  },
  props: {},
  data() {
    return {
      frontImage: 'bmlocal://assets/user/user_img_name_auth_front.jpg',
      backImage: 'bmlocal://assets/user/user_img_name_auth_back.jpg',
      realName: '',
      idCode: ''
    }
  },
  computed: {},
  watch: {},
  created() { },
  methods: {
    onPick(direction = 1) {
      this.$picture.pick({
        maxCount: 1,
        ratioX: 8,
        ratioY: 5,
        allowCrop: true
      }).then(res => {
        const image = (res && res.length && res[0]) || ''
        if (direction === 1) {
          this.frontImage = image
        } else {
          this.backImage = image
        }
        // this.ocrIdCard(1)
      }).catch(err => {
        console.log(err)
        this.$notice.toast({ message: '图片选择失败，请重试！' })
      })
    },
    submit() {
      if (!this.validatePicture(this.frontImage)) {
        return this.$notice.toast({ message: '请选择身份证正面照片' })
      }
      if (!this.validatePicture(this.backImage)) {
        return this.$notice.toast({ message: '请选择身份证反面照片' })
      }
      if (!this.realName) {
        return this.$notice.toast({ message: '请输入真实姓名' })
      }
      if (!this.idCode) {
        return this.$notice.toast({ message: '请输入身份证号码' })
      }
      if (!this.validateIdCard(this.idCode)) {
        return this.$notice.toast({ message: '请输入正确的身份证号码' })
      }
      // 开始上传图片到OSS
      this.uploadOss([this.frontImage, this.backImage])
    },
    uploadOss(images) {
      this.$oss.uploadImage({
        files: images
      }).then(res => {
        // 上传图片成功，提交认证信息
        this.putAuth(res)
      }).catch(err => {
        this.$notice.toast({ message: '上传图片失败，请重试！' })
      })
    },
    putAuth(images) {
      this.$http({
        method: 'PUT',
        name: 'auth.user.name',
        params: {
          name: this.realName,
          idCard: this.idCode,
          idCardImg: `["${images.join('","')}"]`
        },
        errorMsg: '认证失败，请重试！'
      }).then(res => {
        this.$notice.toast({ message: '实名认证成功，请耐心等待审核！' })
        this.$router.setBackParams({ type: 1 })
        this.$router.back({ length: 1, type: 'PUSH' })
      })
    },
    validatePicture(picture) {
      if (/^bmlocal.*/.test(picture)) {
        return false
      }
      if (!picture) {
        return false
      }
      return true
    },
    validateIdCard(cardNo) {
      if (/(^[0-9]{15}$)|(^[0-9]{18}$)|(^[0-9]{17}([0-9]|X|x)$)/.test(cardNo)) {
        return true
      }
      return false
    },
    // TODO: 调用阿里身份证识别接口，需要用base64数据。大致处理方向：
    // 1、pick函数返回base64，再通过js fetch提交（base64会导致anr）
    // 2、Java封装认证请求，js直接传文件路径
    pickToBase64({ maxCount = 1, imageWidth = 0, allowCrop = false }) {
      return new Promise((resolve, reject) => {
        bmImage.pick({
          maxCount,
          imageWidth,
          allowCrop,
          base64: true,
        }, ({ status, errorMsg, data }) => {
          console.log(JSON.stringify(data))
          status === 0 ? resolve(data) : reject({ status, errorMsg, data })
        })
      })
    },
    ocrIdCard(type = 1) {
      this.$http({
        method: 'POST',
        url: 'http://api05.aliyun.venuscn.com/ocr/id-card',
        header: {
          'Authorization': 'APPCODE 84fcd2ba60154f70b7ede5106314b4fd',
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        data: {
          pic: '',
          type: type
        }
      }).then(res => {
        console.log(res)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.icon {
  font-family: alicon;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.text-center {
  text-align: center;
}
.p-3 {
  padding: 30px;
}
.mb-3 {
  margin-bottom: 30px;
}
.mr-3 {
  margin-right: 30px;
}
.mr-1 {
  margin-right: 10px;
}
.text-muted {
  color: #999;
}
.small {
  font-size: 26px;
}
.bg-white {
  background-color: #fff;
}
.rounded {
  border-radius: 6px;
}

.id-image {
  width: 270px;
  height: 200px;
}

.input {
  flex: 1;
  height: 60px;
  font-size: 30px;
  tint-color: #999;
}
</style>
